﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using WWB.SitePointPrivateMessages.Core.Model.DataImport;

namespace WWB.SitePointPrivateMessages.Core.Service
{
    public class XmlFileImportExportService
    {
        public SitePointMessageExport GetMessagesFromXml(string xmlFileName)
        {
            SitePointMessageExport export = null;
            using (var xtr = new XmlTextReader(xmlFileName))
            {
                export = GetMessagesFromXml(xtr);
            }
            return export;
        }

        public SitePointMessageExport GetMessagesFromXml(XmlTextReader reader)
        {
            var serializer = new XmlSerializer(typeof (SitePointMessageExport));
            var export = serializer.Deserialize(reader) as SitePointMessageExport;
            return export;
        }

        public XDocument SerializeMessages(SitePointMessageExport toSerialize)
        {
            if (toSerialize == null) throw new ArgumentNullException("toSerialize");
            var xsz = new XmlSerializer(typeof (SitePointMessageExport));
            var d = new XDocument();
            var xns = new XmlSerializerNamespaces();
            xns.Add("", "");
            using (XmlWriter w = d.CreateWriter())
            {
                xsz.Serialize(w, toSerialize, xns);
            }
            return d;
        }
    }
}
